from rest_framework.permissions import IsAuthenticated
from rest_framework.viewsets import GenericViewSet,ViewSet
from django.conf import settings
from rest_framework_jwt.authentication import JSONWebTokenAuthentication
import json
from datetime import datetime
from buyHigh.utils.buyHighResponse import APIResponse
from .models import UserProfile
from rest_framework.decorators import action
from buyHigh.utils.check_telephone import check_telephone
from .BHthrotting import SMSThrottle
from django.core.cache import cache
# 生产者
from buyHigh.libs.sendSms import get_random_code,sms_settings
from celery_task.celery_sms import celery_send_message
from .serializer import CodeLoginSerializer,UserProfileSerializer
import json

# Create your views here.
class LoginView(GenericViewSet):
    queryset = UserProfile.objects.all()
    serializer_class = None
    def wxlogin(self,request,*args,**kwargs):
        # 验证码登录
        return
    @action(methods=['post'],detail=False)
    def code_login_register(self,request,*args,**kwargs):
        # 验证码登录
        ser=CodeLoginSerializer(data=request.data)
        if ser.is_valid(raise_exception=True):
            return APIResponse(status=200,statusCode=200,code=200,message='success',token=ser.context['token'],data=ser.data)
        else:
            return APIResponse(status=400,statusCode=400,code=400,message='file',data=ser.errors)


class sendSmsView(ViewSet):
    # throttle_classes = [SMSThrottle]
    @action(methods=['post'],detail=False)
    def send_sms(self,request,*args,**kwargs):
        print(request.data["telephone"])
        telephone=request.data['telephone']
        result=check_telephone(telephone)
        if result:
            # 生成验证码
            code=get_random_code.get_rendom_code()
            # 发送短信，添加到任务队列
            celery_send_message.delay(sms_settings.tid, telephone, (code, sms_settings.timeout))
            # 保存验证码
            cache.set(settings.PHONE_CACHE_KEY%request.data['telephone'],code,settings.SMS_CODE_EXPIRE_TIME)
            return APIResponse(status=200,statusCode=200,code=200,message='success')
        else:
            return APIResponse(status=200,statusCode=200,code=200,message='手机号格式错误')


class ProfileView(GenericViewSet):
    queryset = UserProfile.objects.all()
    permission_classes = [IsAuthenticated]
    authentication_classes = [JSONWebTokenAuthentication]
    serializer_class = UserProfileSerializer
    def get_user_info(self,request,*args,**kwargs):
        user=request.user
        ser=UserProfileSerializer(user)
        return APIResponse(data=ser.data,status=200,statusCode=200,code=200,message='success')
    def update_user_icon(self,request,*args,**kwargs):
        user=request.user
        icon=request.data.get('file')
        if icon:
            # 存储头像
            user.icon=icon
            user.save()
        # json_icon=json.dumps({'icon':"/media/%s"%(user.icon)})
        return APIResponse(status=200,statusCode=200,code=200,message='success',icon='/media/%s'%str(user.icon))
    def update_user_info(self,request,*args,**kwargs):
        user=request.user
        request.data['city']='-'.join(request.data['city'])
        print(request.data)
        ser=UserProfileSerializer(user,data=request.data,partial=True)
        # 部分更新
        if ser.is_valid(raise_exception=True):
            ser.save()
            return APIResponse(status=200,statusCode=200,code=200,message='success',data=ser.data)

